<template>
  <div class="note-editor">
    <div class="editor-header">
      <div class="header-left">
        <button @click="goBack" class="btn">
          <span class="icon">←</span>
          返回
        </button>
        <h1>{{ isEditing ? '编辑' : '新建' }}{{ getNoteTypeText() }}</h1>
      </div>
      <div class="header-right">
        <button @click="saveNote" class="btn btn-primary" :disabled="!canSave">
          保存
        </button>
      </div>
    </div>
    
    <div class="editor-content">
      <!-- 基础信息 -->
      <div class="form-section">
        <label class="form-label">标题</label>
        <input 
          v-model="noteData.title" 
          type="text" 
          class="input" 
          placeholder="输入标题..."
        />
      </div>
      
      <div class="form-section">
        <label class="form-label">标签</label>
        <input 
          v-model="tagInput" 
          type="text" 
          class="input" 
          placeholder="输入标签，用逗号分隔..."
          @keydown.enter="addTag"
        />
        <div class="tags-display">
          <span 
            v-for="tag in noteData.tags" 
            :key="tag" 
            class="tag"
            @click="removeTag(tag)"
          >
            {{ tag }} ×
          </span>
        </div>
      </div>
      
      <!-- 代码笔记特有字段 -->
      <template v-if="noteType === 'code'">
        <div class="form-section">
          <label class="form-label">编程语言</label>
          <select v-model="codeData.language" class="input">
            <option value="">选择语言</option>
            <option value="javascript">JavaScript</option>
            <option value="typescript">TypeScript</option>
            <option value="vue">Vue</option>
            <option value="react">React</option>
            <option value="python">Python</option>
            <option value="java">Java</option>
            <option value="css">CSS</option>
            <option value="html">HTML</option>
            <option value="sql">SQL</option>
            <option value="bash">Bash</option>
          </select>
        </div>
        
        <div class="form-section">
          <label class="form-label">描述</label>
          <textarea 
            v-model="codeData.description" 
            class="textarea" 
            placeholder="代码描述..."
          />
        </div>
        
        <div class="form-section">
          <label class="form-label">代码</label>
          <textarea 
            v-model="codeData.code" 
            class="textarea code-textarea" 
            placeholder="输入代码..."
          />
        </div>
      </template>
      
      <!-- 日记特有字段 -->
      <template v-if="noteType === 'diary'">
        <div class="form-section">
          <label class="form-label">内容 (支持 Markdown)</label>
          <div class="markdown-editor">
            <div class="editor-toolbar">
              <button type="button" @click="insertMarkdown('**', '**')" class="toolbar-btn">粗体</button>
              <button type="button" @click="insertMarkdown('*', '*')" class="toolbar-btn">斜体</button>
              <button type="button" @click="insertMarkdown('# ', '')" class="toolbar-btn">标题</button>
              <button type="button" @click="insertMarkdown('```\n', '\n```')" class="toolbar-btn">代码块</button>
              <button type="button" @click="insertMarkdown('`', '`')" class="toolbar-btn">行内代码</button>
              <button type="button" @click="insertMarkdown('- ', '')" class="toolbar-btn">列表</button>
            </div>
            <textarea 
              v-model="noteData.content" 
              class="textarea markdown-textarea" 
              placeholder="输入日记内容，支持 Markdown 格式..."
            />
          </div>
        </div>
      </template>
      
      <!-- 待办事项特有字段 -->
      <template v-if="noteType === 'todo'">
        <div class="form-section">
          <label class="form-label">分类</label>
          <select v-model="todoData.category" class="input">
            <option value="">选择分类</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </option>
          </select>
        </div>
        
        <!-- 待办事项列表 -->
        <div class="form-section">
          <label class="form-label">待办事项</label>
          <div class="todo-items">
            <div 
              v-for="(todo, index) in todoData.todos" 
              :key="todo.id" 
              class="todo-item"
            >
              <div class="todo-inputs">
                <input 
                  v-model="todo.title" 
                  type="text" 
                  class="input" 
                  placeholder="待办事项标题"
                />
                <textarea 
                  v-model="todo.description" 
                  class="textarea" 
                  placeholder="描述（可选）"
                />
                <div class="todo-options">
                  <select v-model="todo.priority" class="input">
                    <option value="low">低优先级</option>
                    <option value="medium">中优先级</option>
                    <option value="high">高优先级</option>
                  </select>
                  <input 
                    v-model="todo.dueDate" 
                    type="date" 
                    class="input"
                  />
                </div>
              </div>
              <button @click="removeTodo(index)" class="btn btn-danger">删除</button>
            </div>
            <button @click="addTodo" class="btn">添加待办事项</button>
          </div>
        </div>
      </template>
      
      <!-- 通用内容 -->
      <div class="form-section">
        <label class="form-label">内容</label>
        <textarea 
          v-model="noteData.content" 
          class="textarea" 
          placeholder="输入内容..."
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useNoteStore } from '@/stores/noteStore';
import { generateId } from '@/utils/helpers';
import { NoteType, TodoStatus } from '@/types';
import type { Note, CodeNote, DiaryNote, TodoNote, TodoItem } from '@/types';

const route = useRoute();
const router = useRouter();
const noteStore = useNoteStore();

const noteType = computed(() => route.params.type as string);
const noteId = computed(() => route.params.id as string);
const isEditing = computed(() => !!noteId.value);

// 基础数据
const noteData = ref({
  title: '',
  content: '',
  tags: [] as string[]
});

// 代码笔记数据
const codeData = ref({
  language: '',
  code: '',
  description: ''
});

// 日记数据 - 已简化，不再需要额外字段
const diaryData = ref({});

// 待办事项数据
const todoData = ref({
  category: '',
  todos: [] as TodoItem[]
});

const tagInput = ref('');
const categories = computed(() => noteStore.categories);

const canSave = computed(() => {
  return noteData.value.title.trim() !== '';
});

const getNoteTypeText = () => {
  const typeMap: Record<string, string> = {
    code: '代码笔记',
    diary: '日记',
    todo: '待办事项'
  };
  return typeMap[noteType.value] || '笔记';
};

const goBack = () => {
  router.back();
};

const addTag = () => {
  const tag = tagInput.value.trim();
  if (tag && !noteData.value.tags.includes(tag)) {
    noteData.value.tags.push(tag);
    tagInput.value = '';
  }
};

const removeTag = (tag: string) => {
  const index = noteData.value.tags.indexOf(tag);
  if (index > -1) {
    noteData.value.tags.splice(index, 1);
  }
};

const addTodo = () => {
  const newTodo: TodoItem = {
    id: generateId(),
    title: '',
    description: '',
    status: TodoStatus.PENDING,
    category: todoData.value.category,
    priority: 'medium',
    createdAt: new Date(),
    updatedAt: new Date()
  };
  todoData.value.todos.push(newTodo);
};

const removeTodo = (index: number) => {
  todoData.value.todos.splice(index, 1);
};

// Markdown 编辑器工具函数
const insertMarkdown = (before: string, after: string) => {
  const textarea = document.querySelector('.markdown-textarea') as HTMLTextAreaElement;
  if (!textarea) return;
  
  const start = textarea.selectionStart;
  const end = textarea.selectionEnd;
  const selectedText = noteData.value.content.substring(start, end);
  
  const newText = noteData.value.content.substring(0, start) + 
                  before + selectedText + after + 
                  noteData.value.content.substring(end);
  
  noteData.value.content = newText;
  
  // 设置光标位置
  setTimeout(() => {
    textarea.focus();
    textarea.setSelectionRange(start + before.length, end + before.length);
  }, 0);
};

const saveNote = () => {
  if (!canSave.value) return;
  
  const note: Partial<Note> = {
    title: noteData.value.title,
    content: noteData.value.content,
    tags: noteData.value.tags,
    type: noteType.value as NoteType
  };
  
  if (noteType.value === 'code') {
    (note as Partial<CodeNote>).language = codeData.value.language;
    (note as Partial<CodeNote>).code = codeData.value.code;
    (note as Partial<CodeNote>).description = codeData.value.description;
  } else if (noteType.value === 'diary') {
    // 日记只需要标题和内容，不需要额外字段
  } else if (noteType.value === 'todo') {
    (note as Partial<TodoNote>).category = todoData.value.category;
    (note as Partial<TodoNote>).todos = todoData.value.todos;
  }
  
  if (isEditing.value) {
    noteStore.updateNote(noteId.value, note);
  } else {
    noteStore.addNote(note as Note);
  }
  
  router.back();
};

const loadNote = () => {
  if (!isEditing.value) return;
  
  const note = noteStore.notes.find(n => n.id === noteId.value);
  if (!note) return;
  
  noteData.value.title = note.title;
  noteData.value.content = note.content;
  noteData.value.tags = [...note.tags];
  
  if (note.type === NoteType.CODE) {
    const codeNote = note as CodeNote;
    codeData.value.language = codeNote.language;
    codeData.value.code = codeNote.code;
    codeData.value.description = codeNote.description || '';
  } else if (note.type === NoteType.DIARY) {
    // 日记只需要标题和内容，不需要额外字段
  } else if (note.type === NoteType.TODO) {
    const todoNote = note as TodoNote;
    todoData.value.category = todoNote.category;
    todoData.value.todos = [...todoNote.todos];
  }
};

onMounted(() => {
  loadNote();
});
</script>

<style lang="scss" scoped>
.note-editor {
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-lg;
    padding-bottom: $spacing-md;
    border-bottom: $border-width solid $border-color;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: $spacing-md;
      
      h1 {
        font-size: $font-size-xl;
        color: $primary-color;
        margin: 0;
      }
    }
  }
  
  .editor-content {
    .form-section {
      margin-bottom: $spacing-lg;
      
      .form-label {
        display: block;
        font-weight: bold;
        color: $text-color;
        margin-bottom: $spacing-sm;
      }
      
      .tags-display {
        display: flex;
        gap: $spacing-xs;
        flex-wrap: wrap;
        margin-top: $spacing-sm;
        
        .tag {
          background-color: $hover-color;
          color: $text-color;
          padding: $spacing-xs $spacing-sm;
          border-radius: $border-radius;
          font-size: $font-size-small;
          cursor: pointer;
          
          &:hover {
            background-color: #ff4757;
            color: $secondary-color;
          }
        }
      }
      
      .todo-items {
        .todo-item {
          display: flex;
          gap: $spacing-md;
          margin-bottom: $spacing-md;
          padding: $spacing-md;
          border: $border-width solid $border-color;
          border-radius: $border-radius;
          background-color: $secondary-color;
          
          .todo-inputs {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: $spacing-sm;
            
            .todo-options {
              display: flex;
              gap: $spacing-sm;
              
              @media (max-width: $breakpoint-mobile) {
                flex-direction: column;
              }
            }
          }
        }
      }
      
      .code-textarea {
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: $font-size-small;
        line-height: 1.4;
      }
      
      .markdown-editor {
        .editor-toolbar {
          display: flex;
          gap: $spacing-xs;
          margin-bottom: $spacing-sm;
          flex-wrap: wrap;
          
          .toolbar-btn {
            padding: $spacing-xs $spacing-sm;
            border: $border-width solid $border-color;
            background-color: $secondary-color;
            color: $text-color;
            border-radius: $border-radius;
            font-size: $font-size-small;
            cursor: pointer;
            
            &:hover {
              background-color: $hover-color;
            }
          }
        }
        
        .markdown-textarea {
          font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
          font-size: $font-size-small;
          line-height: 1.4;
          min-height: 300px;
        }
      }
    }
  }
  
  @media (max-width: $breakpoint-mobile) {
    .editor-header {
      flex-direction: column;
      gap: $spacing-md;
      align-items: stretch;
      
      .header-left {
        flex-direction: column;
        gap: $spacing-sm;
      }
    }
  }
}
</style> 